#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');

console.log('Helm file update');

if (process.argv.length !== 4) {
  console.log('Incorrect number of arguments');
  process.exit(1);
}

const chartFolder = process.argv[2];
const pkgFilePath = process.argv[3];

const pkgFile = JSON.parse(fs.readFileSync(pkgFilePath, 'utf8'));
const chartFile = path.join(chartFolder, 'Chart.yaml');
const valuesFile = path.join(chartFolder, 'values.yaml');

if (!fs.existsSync(chartFolder)) {
  console.log('Charts folder does not exist');
  process.exit(1);
}

// --------------------------------------------------------------------------------
// Chart.yaml updates (annotations)
// --------------------------------------------------------------------------------
const chart = yaml.load(fs.readFileSync(chartFile, 'utf8'));
let chartUpdated = false;

if (pkgFile.rancher?.annotations) {
  chart.annotations = chart.annotations || {};
  Object.entries(pkgFile.rancher.annotations).forEach(([key, value]) => {
    if (chart.annotations[key] !== value) {
      chart.annotations[key] = value;
      chartUpdated = true;
    }
  });
}

if (chartUpdated) {
  fs.writeFileSync(chartFile, yaml.dump(chart), 'utf8');
  console.log('Updated Chart.yaml annotations');
}

// --------------------------------------------------------------------------------
// values.yaml updates (endpoints)
// --------------------------------------------------------------------------------
const values = yaml.load(fs.readFileSync(valuesFile, 'utf8'));

// Get package metadata from package.json
const pkgName = pkgFile.name;
const pkgVersion = pkgFile.version;
const pkgFullName = `${ pkgName }-${ pkgVersion }`;

// Determine build type from environment
const isGitHubBuild = process.env.GITHUB_BUILD === 'true';

// Set endpoints based on build type
if (isGitHubBuild) {
  const githubSource = process.env.GITHUB_SOURCE;
  const githubBranch = process.env.GITHUB_BRANCH;

  values.plugin.endpoint = `https://raw.githubusercontent.com/${ githubSource }/${ githubBranch }/extensions/${ pkgName }/${ pkgVersion }`;
} else {
  const imagePrefix = process.env.IMAGE_PREFIX || '';
  const baseExt = process.env.BASE_EXT;

  values.plugin.endpoint = `http://${ imagePrefix }${ baseExt }-svc.cattle-ui-plugin-system:8080/plugin/${ pkgFullName }`;
}

// Always set compressedEndpoint as endpoint + .tgz
values.plugin.compressedEndpoint = `${ values.plugin.endpoint }.tgz`;

// Write updated values.yaml
fs.writeFileSync(valuesFile, yaml.dump(values, { quotingType: '"' }), 'utf8');
console.log('Updated values.yaml endpoints:');
console.log(`- endpoint: ${ values.plugin.endpoint }`);
console.log(`- compressedEndpoint: ${ values.plugin.compressedEndpoint }`);
